<template>
  <tl-sub-page :render="render" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-dialog" width="1000px" top="52px" @open="open" @close="close">
    <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="120px" :disabled="disableEditSubmit || stateApproval">
      <el-row>
        <el-col :span="8">
          <el-form-item label="开始时间" prop="begintimeDate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.begintimeDate" type="date" placeholder="开始时间" value-format="yyyy-MM-dd" :picker-options="expireTimeOption" @change="clearRoom"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="" label-width="10px" prop="begintimeTime" :rules="rules.validateRequire">
            <el-time-select
              @change="clearRoom"
              v-model="model.begintimeTime"
              placeholder="选择时间"
              editable
              :clearable="false"
              :picker-options="{
                start: '00:00',
                step: '00:05',
                end: '24:00'
              }"
            >
            </el-time-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="结束时间" prop="endtimeDate" :rules="rules.validateRequire">
            <el-date-picker v-model="model.endtimeDate" type="date" placeholder="结束时间" value-format="yyyy-MM-dd" :picker-options="expireTimeOption" @change="clearRoom"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="" label-width="10px" prop="endtimeTime" :rules="rules.validateRequire">
            <el-time-select
              @change="clearRoom"
              v-model="model.endtimeTime"
              placeholder="选择时间"
              editable
              :picker-options="{
                start: '00:00',
                step: '00:05',
                end: '24:00'
              }"
            >
            </el-time-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="会议主题" prop="name" :rules="rules.validateRequire">
            <el-input v-model="model.name" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会议室" prop="meetroomid" :rules="rules.validateRequire">
            <tl-ref-select-room v-model="model.meetroomid" :initDisplayData.sync="model.airlinecompany" :requireModel.sync="queryBoardItemModel" meetRoomType="company" @open="initSelectMeetRoom" @updateRequire="updateRequire" :currentRecord="this.model"></tl-ref-select-room>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="会议内容" prop="boardcontent">
            <el-input v-model="model.boardcontent" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="参会人数" prop="attendance" :rules="rules.validateRequire">
            <el-input-number style="width: 350px" v-model="model.attendance"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <tl-help  style="position: absolute;left: 20px;top: 10px;">
            音响设备使用说明：<br/>
            1、打开音响设备
            <img style="width:35px" src="/static/images/meetRoom/switch.png" />
            开关键，电脑插上音频线
            <img style="width:35px" src="/static/images/meetRoom/audioLine.png" />
            ，电脑自动弹出对话框“Realtek高清晰音频管理器”，选择“耳机”；<br/>
            2、调试电脑自带声音，鼠标右击电脑右下方
            <img style="width:25px" src="/static/images/meetRoom/volume.png" />
            键，打开声音设置，输出设备：扬声器，输入设备：麦克风阵列，可以进行公放视频。<br/><br/>
            <b>适用第三、第六视频会议设备：</b><br/>
            将宝利通视频设备USB插入电脑，右击电脑右下方
            <img style="width:25px" src="/static/images/meetRoom/volume.png" />
            键，打开声音设置，选择“回音消除话筒（Polycom Studio Audio）”，点击确定即可单独使用音频效果播放视频。视频会议设备连接电脑，进入腾讯会议，设置音频，即可完成视频会议连接。
          </tl-help>
          <el-form-item label="会议配置">
            <el-checkbox-group v-model="selectedSourcelists">
              <el-checkbox v-for="item in codeModel.sourcelistList" :key="item.code" :label="item.code.toString()">
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="其他配置" prop="preparerequest">
            <el-input v-model="model.preparerequest" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="会务服务">
            <el-checkbox-group v-model="selectedServices" @change="doSelectService">
              <el-checkbox v-for="item in serviceList" :key="item.code" :label="item.code.toString()">
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="service.welcomevisiable">
        <el-col :span="12">
          <el-form-item label="欢迎屏内容" prop="welcomeinfo" :rules="rules.validateRequire">
            <el-input v-model="model.welcomeinfo" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示时间" prop="welcometime" :rules="rules.validateRequire">
            <el-input v-model="model.welcometime" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="service.signvisiable || service.teavisiable">
        <el-col :span="12" v-if="service.signvisiable">
          <el-form-item label="桌签内容" prop="signinfo" :rules="rules.validateRequire">
            <el-input v-model="model.signinfo" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="service.teavisiable">
          <el-form-item label="茶歇服务" prop="teainfo" :rules="rules.validateRequire">
            <el-input v-model="model.teainfo" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="service.othervisiable">
        <el-col :span="24">
          <el-form-item label="其他" prop="otherservice" :rules="rules.validateRequire">
            <el-input v-model="model.otherservice" type="textarea" :rows="2" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="会议主持人" prop="hostusercode">
            <tl-ref-user v-model="model.hostusercode" :initDisplayData.sync="model.disphostusercode" dataType="code" :singleSelect="true" :externalQueryParam="{qry_whereSql:'EXTENDFIELD1 IS NOT NULL AND ENABLED = 1',qry_nodimission:'0'}" ></tl-ref-user>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="'内部参会(' + innerPeopleCount + '人)'" prop="partinneruser">
            <tl-ref-user v-model="model.partinnerusercode" :initDisplayData.sync="model.partinnerusername" dataType="code" :externalQueryParam="{qry_whereSql:'EXTENDFIELD1 IS NOT NULL AND ENABLED = 1',qry_nodimission:'0'}" ></tl-ref-user>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="审批流程" prop="flowid">
            <el-select v-model="model.flowid">
              <el-option v-for="item in codeModel.flowList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="telephone" :rules="rules.validateRequire">
            <el-input v-model="model.telephone" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider>
        <el-link :icon="displayMore ? 'el-icon-upload2' : 'el-icon-download'" type="primary" @click="displayMore = !displayMore">{{ displayMore ? '收起' : '更多信息' }}</el-link>
      </el-divider>
      <el-row v-show="displayMore">
        <el-col :span="12">
          <el-form-item label="申请人" prop="username">
            <el-input v-model="model.username" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工号" prop="usercode">
            <el-input v-model="model.usercode" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="displayMore">
        <el-col :span="12">
          <el-form-item label="公司" prop="orgcode">
            <el-input v-model="model.disporgcode" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属部门" prop="deptcode">
            <el-input v-model="model.dispdeptcode" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <tl-approval-history ref="history" sourceType="MeetRoomApply" :sourceId="model.id" />
    <div slot="footer" class="dialog-footer">
      <el-button :type="disableEditSubmit === false ? 'text' : 'primary'" @click="doCancelEdit">取消</el-button>
      <el-button type="primary" @click="doSubmitEdit" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave"><svg-icon icon-class="save" />保存</el-button>
      <el-button type="primary" @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval"><svg-icon icon-class="send" />提交审批</el-button>
      <el-button type="primary" @click="$refs.history.visible = true" :disabled="disableApprovalHistory"><svg-icon icon-class="list" />审批历史</el-button>
      <el-button type="primary" @click="doDelApproval" :loading="delApprovalLoading" v-if="!disableEditSubmit" :disabled="disableDelApproval"><svg-icon icon-class="undo" />取消审批</el-button>
    </div>
  </tl-sub-page>
</template>

<script>
import { formatDate } from '@tapui/utils/date'
/** mixins */
import { mixin_approval_edit } from '@tapui/mixins/mixin_approval_edit'
/** 子组件 */
import tlRefSelectRoom from '../meetRoomManage/selectRoomIndex'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlRefSelectRoom },
  data() {
    return {
      moduleTitle: '会议室预订申请',
      urlPrefix: '/meet/roomApply/',
      url: {
        // 额外的url
      },
      queryBoardItemModel: {
        begintime: '',
        endtime: '',
        count: 0
      },
      selectedSourcelists: [],
      selectedServices: [],
      serviceList: [
        { code: 'welcomevisiable', name: '欢迎屏准备' },
        { code: 'signvisiable', name: '桌签准备' },
        { code: 'teavisiable', name: '茶歇准备' },
        { code: 'othervisiable', name: '其他' }
      ],
      service: {
        welcomevisiable: false,
        signvisiable: false,
        teavisiable: false,
        othervisiable: false
      },
      displayMore: false,
      expireTimeOption: {
        disabledDate(date) {
          // 当天可选
          return date.getTime() < Date.now() - 24 * 60 * 60 * 1000
        }
      }
    }
  },
  computed: {
    innerPeopleCount() {
      if (this.model.partinnerusercode) {
        return this.model.partinnerusercode.split(',').length
      } else {
        return 0
      }
    },
    // 禁用取消审批
    disableDelApproval() {
      return this.stateAdd || this.stateEdit
    }
  },
  methods: {
    doAdd() {
      this.saveLoading = true
      // 增加唯一单号
      this.$set(this.model, 'billuid', this.uid)
      postAction(this.url.add, this.model)
        .then((res) => {
          if (res.success) {
            this.$tap.message('添加成功', 'success')
            this.queryData(res.result.id)
            this.isAdd = false
            window.parent.postMessage('submitAfter:' + res.result.id, '*')
          } else {
            this.$tap.alert(res.message, 'warning')
          }
          this.afterSubmit()
          this.saveLoading = false
        })
        .catch((err) => {
          this.saveLoading = false
        })
    },
    /** 发送事件 */
    postMCRMessage() {
       window.parent.postMessage('submitAfter:' + this.model.id, '*')
    },
    doSelectService() {
      Object.keys(this.service).forEach(key => {
        if (this.selectedServices.includes(key)) {
          this.service[key] = true
        } else {
          this.service[key] = false
          if (key === 'welcomevisiable') {
            this.$set(this.model, 'welcomeinfo', '')
            this.$set(this.model, 'welcometime', '')
          }
          if (key === 'signvisiable') {
            this.$set(this.model, 'signinfo', '')
          }
          if (key === 'teavisiable') {
            this.$set(this.model, 'teainfo', '')
          }
          if (key === 'othervisiable') {
            this.$set(this.model, 'otherservice', '')
          }
        }
      })
    },
    /** 打开会议室列表，初始化 */
    initSelectMeetRoom() {
      this.$set(this.queryBoardItemModel, 'begintimeTime', `${this.model.begintimeTime}` === 'null' ? '' : `${this.model.begintimeTime}`)
      this.$set(this.queryBoardItemModel, 'endtimeTime', `${this.model.endtimeTime}` === 'null' ? '' : `${this.model.endtimeTime}`)
      this.$set(this.queryBoardItemModel, 'begintimeDate', `${this.model.begintimeDate}` === 'null' ? '' : `${this.model.begintimeDate}`)
      this.$set(this.queryBoardItemModel, 'endtimeDate', `${this.model.endtimeDate}` === 'null' ? '' : `${this.model.endtimeDate}`)
      this.$set(this.queryBoardItemModel, 'count', this.innerPeopleCount)
    },
    /** 更新会议室选择数据*/
    updateRequire(requireModel) {
      this.queryBoardItemModel = requireModel
      this.$set(this.model, 'begintimeTime', this.queryBoardItemModel.begintimeTime)
      this.$set(this.model, 'begintimeDate', this.queryBoardItemModel.begintimeDate)
      this.$set(this.model, 'endtimeTime', this.queryBoardItemModel.endtimeTime)
      this.$set(this.model, 'endtimeDate', this.queryBoardItemModel.endtimeDate)
    },
    assignDefaultValue() {
      if (this.isAdd) {
        if (this.codeModel.flowList && this.codeModel.flowList.length > 0) {
          this.$set(this.model, 'flowid', parseInt(this.codeModel.flowList[0].id))
        }
        this.$set(this.model, 'orgcode', this.org.code)
        this.$set(this.model, 'disporgcode', this.org.name)
        this.$set(this.model, 'deptcode', this.dept.code)
        this.$set(this.model, 'dispdeptcode', this.dept.fullname)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'telephone', this.user.mobile)
        if (!this.model.begintime) {
          let now = formatDate(new Date(), 'yyyy-MM-dd')
          this.$set(this.model, 'begintime', now + ' 09:00:00')
          this.$set(this.model, 'endtime', now + ' 11:00:00')
        }
      }
    },
    loaded() {
      // 页面加载完毕执行
      if (!this.isAdd && this.model.docno) {
        this.title = this.title + `（单据编号：${this.model.docno}）`
      }
      // 将会议室配置转成数组类型
      if (this.model.sourcelist) {
        this.selectedSourcelists = this.model.sourcelist.split(',')
      } else {
        this.selectedSourcelists = []
      }
      this.processTime()
      // 会议服务
      this.selectedServices = []
      if (this.model.welcomeinfo) {
        this.selectedServices.push('welcomevisiable')
      }
      if (this.model.signinfo) {
        this.selectedServices.push('signvisiable')
      }
      if (this.model.teainfo) {
        this.selectedServices.push('teavisiable')
      }
      if (this.model.otherservice) {
        this.selectedServices.push('othervisiable')
      }
      this.doSelectService()
    },
    /** 重写查询数据 */
    queryData(id) {
      if (!this.url.load) {
        this.$tap.alert('请设置load地址!', 'warning')
        return
      }
      return getAction(this.url.load, { id: id }).then(res => {
        if (res.success) {
          this.model = res.result
          this.processTime()
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    /** 格式化日期 */
    processTime() {
      // 时间拆分
      if (this.model.begintime) {
        let beginArr = this.model.begintime.split(' ')
        this.$set(this.model, 'begintimeDate', beginArr[0])
        this.$set(this.model, 'begintimeTime', beginArr[1].substring(0, 5))
      }
      if (this.model.endtime) {
        let endArr = this.model.endtime.split(' ')
        this.$set(this.model, 'endtimeDate', endArr[0])
        this.$set(this.model, 'endtimeTime', endArr[1].substring(0, 5))
      }
    },
    // 提交
    beforeSubmit() {
      this.model.begintime = `${this.model.begintimeDate} ${this.model.begintimeTime}`
      this.model.endtime = `${this.model.endtimeDate} ${this.model.endtimeTime}`
      let beginTime = new Date(this.model.begintime)
      let endTime = new Date(this.model.endtime)
      if (endTime <= beginTime) {
        this.$tap.alert('会议结束时间不能早于会议开始时间！')
        return false
      }
      this.model.sourcelist = this.selectedSourcelists.join(',')
      return true
    },
    beforeApproval() {
      let isValid = this.beforeSubmit()
      if (isValid === false) {
        this.submitLoading = false
      }
      return isValid
    },
    afterApproval() {
      this.postMCRMessage()
    },
    afterSubmit() {
      if (this.model.id && parseInt(this.model.id) > 0) {
        this.postMCRMessage()
      }
    },
    /** 打开会议室id参照 */
    opentoaBoardroomItemRefDialog() {
      this.$refs.toaBoardroomItemRef.visible = true
    },
    /** 获取会议室id参数数据 */
    gettoaBoardroomItemRefData(selectionRow, selectKey, selectionValue) {
      this.$set(this.model, 'meetroomid', selectionRow.code)
    },
    /** 清空已选会议室 **/
    clearRoom() {
      if (this.model.meetroomid) {
        this.$tap.alert('为避免时间冲突，请重新选择会议室！')
        this.$set(this.model, 'meetroomid', '')
        this.$set(this.model, 'airlinecompany', '')
      }
    }
  }
}
</script>
